﻿using System;
using System.Collections.Generic;
using System.Text;
using Abp.Dependency;
using Abp.Domain.Entities.Auditing;
using Abp.Domain.Repositories;
using Abp.Threading.BackgroundWorkers;
using Abp.Threading.Timers;
using Yozeev.BusinessLogic;
using Yozeev.BusinessLogic.DeviceManagement.DomainService;

namespace Yozeev.BackgroundWorkers
{
    public class OnlineDevicesManageWorker: PeriodicBackgroundWorkerBase, ISingletonDependency
    {
        private readonly IDeviceCache _deviceCache;

        private readonly IRepository<Device, Guid> _deviceRepository;

        public OnlineDevicesManageWorker(AbpTimer timer, 
            IDeviceCache deviceCache,
            IRepository<Device, Guid> deviceRepository) : base(timer)
        {
            _deviceCache = deviceCache;
            _deviceRepository = deviceRepository;
            Timer.Period = 1000 * 60 * 30; // process every one minute
        }

        protected override async void DoWork()
             {

            long currentTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
            //Logger.Error("自动判断机器在线程序正在运行~~~~,当前时间为:" + currentTime);
            Dictionary<string, long> dic = _deviceCache.GetDictionary();
            List<string> keys = new List<string>();
            foreach (var data in dic)
            {
                long offset = currentTime - data.Value;
                if (offset > 60 * 1000 * 2)
                {
                    //时长超过2分钟
                    keys.Add(data.Key);
                    //更新数据库
                    Device device = this._deviceRepository.Get(new Guid(data.Key));
                    device.DeviceStatus = DeviceStatusEnum.Closing;
                    await this._deviceRepository.UpdateAsync(device);
                }
            }

            _deviceCache.Remove(keys);
        }
    }
}
